package com.swotxu.mall.ware.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.swotxu.common.constant.WareConstant;
import com.swotxu.common.utils.PageUtils;
import com.swotxu.common.utils.Query;
import com.swotxu.mall.ware.dao.PurchaseDao;
import com.swotxu.mall.ware.entity.PurchaseDetailEntity;
import com.swotxu.mall.ware.entity.PurchaseEntity;
import com.swotxu.mall.ware.service.PurchaseDetailService;
import com.swotxu.mall.ware.service.PurchaseService;
import com.swotxu.mall.ware.service.WareSkuService;
import com.swotxu.mall.ware.vo.MergeVo;
import com.swotxu.mall.ware.vo.PurchaseDoneVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {

    @Autowired
    PurchaseDetailService purchaseDetailService;
    @Autowired
    WareSkuService wareSkuService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPageUnreceivePurchase(Map<String, Object> params) {

        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new LambdaQueryWrapper<PurchaseEntity>().eq(PurchaseEntity::getStatus, WareConstant.PurchaseStatusEnum.CREATED.getCode())
                        .or().eq(PurchaseEntity::getStatus, WareConstant.PurchaseStatusEnum.ASSIGNED.getCode())
        );

        return new PageUtils(page);

    }

    @Override
    @Transactional
    public void mergePurchase(MergeVo mergeVo) {
        // 筛选出待合并的采购项状态为0,1的数据
        List<Integer> statusList = Arrays.asList(WareConstant.PurchaseDetailStatusEnum.CREATED.getCode()
                , WareConstant.PurchaseDetailStatusEnum.ASSIGNED.getCode());
        LambdaQueryWrapper<PurchaseDetailEntity> detailUpdateWrapper = new LambdaQueryWrapper<PurchaseDetailEntity>()
                .in(PurchaseDetailEntity::getId, mergeVo.getItems())
                .in(PurchaseDetailEntity::getStatus, statusList);
        List<PurchaseDetailEntity> detailEntityList = purchaseDetailService.list(detailUpdateWrapper);

        if (CollectionUtils.isEmpty(detailEntityList)) {
            log.info("待合并的有效采购项数据为空！all: {}", mergeVo.getItems());
            return;
        }
        // 若未选择关联采购单，则新建采购单
        Long purchaseId = mergeVo.getPurchaseId();
        if (purchaseId == null) {
            PurchaseEntity purchaseEntity = new PurchaseEntity();
            purchaseEntity.setCreateTime(new Date());
            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.CREATED.getCode());
            this.save(purchaseEntity);
            purchaseId = purchaseEntity.getId();
        }
        // 更新采购项状态和所属采购单
        Long finalPurchaseId = purchaseId;
        List<PurchaseDetailEntity> detailEntities = detailEntityList.stream().peek(entity -> {
            entity.setPurchaseId(finalPurchaseId);
            entity.setStatus(WareConstant.PurchaseDetailStatusEnum.ASSIGNED.getCode());
        }).collect(Collectors.toList());

        purchaseDetailService.updateBatchById(detailEntities);

        // 更新采购单时间
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setUpdateTime(new Date());
        purchaseEntity.setId(finalPurchaseId);
        this.updateById(purchaseEntity);
    }

    @Override
    @Transactional
    public void received(List<Long> purchaseIds) {
        // 1、确认当前采购单是新建或已分配状态
        List<Integer> statusList = Arrays.asList(WareConstant.PurchaseStatusEnum.CREATED.getCode()
                , WareConstant.PurchaseStatusEnum.ASSIGNED.getCode());
        // 筛选出指定状态、指定id的采购单
        LambdaQueryWrapper<PurchaseEntity> lambdaQueryWrapper = new LambdaQueryWrapper<PurchaseEntity>()
                .in(PurchaseEntity::getId, purchaseIds)
                .in(PurchaseEntity::getStatus, statusList);

        List<PurchaseEntity> purchaseEntityList = this.getBaseMapper().selectList(lambdaQueryWrapper);

        if (!CollectionUtils.isEmpty(purchaseEntityList)) {
            List<Long> validPurchaseIds = purchaseEntityList.stream().map(PurchaseEntity::getId).collect(Collectors.toList());
            // 2、改变采购单的状态
            LambdaUpdateWrapper<PurchaseEntity> purchaseUpdateWrapper = new LambdaUpdateWrapper<PurchaseEntity>()
                    .in(PurchaseEntity::getId, validPurchaseIds)
                    .set(PurchaseEntity::getUpdateTime, new Date())
                    .set(PurchaseEntity::getStatus, WareConstant.PurchaseStatusEnum.RECEIVE.getCode());
            this.update(purchaseUpdateWrapper);
            /*List<PurchaseEntity> entities = purchaseEntityList.stream()
                    .peek(purchaseEntity -> purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.RECEIVE.getCode()))
                    .collect(Collectors.toList());
            this.updateBatchById(entities);*/

            // 3、改变采购单关联的采购项的状态
            LambdaUpdateWrapper<PurchaseDetailEntity> updateWrapper = new LambdaUpdateWrapper<PurchaseDetailEntity>()
                    .in(PurchaseDetailEntity::getPurchaseId, validPurchaseIds)
                    .set(PurchaseDetailEntity::getStatus, WareConstant.PurchaseDetailStatusEnum.BUYING.getCode());
            purchaseDetailService.update(updateWrapper);
        }
    }

    @Override
    @Transactional
    public void done(PurchaseDoneVo purchaseDoneVo) {
        // 1、改变采购单状态（只有所有采购项成功，采购单才成功）
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(purchaseDoneVo.getId());
        purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.FINISH.getCode());

        // 2、改变采购项状态
        List<PurchaseDetailEntity> updateDetailEntities = purchaseDoneVo.getItems().stream().map(itemVo -> {
            PurchaseDetailEntity detailEntity = new PurchaseDetailEntity();
            detailEntity.setId(itemVo.getItemId());
            // 若采购项状态无异常，则设置为完成，否则设置为异常
            if (!WareConstant.PurchaseDetailStatusEnum.HASERROR.equalsCodeTo(itemVo.getStatus())) {
                detailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.FINISH.getCode());
            } else {
                detailEntity.setStatus(itemVo.getStatus());
                // 当有一个采购项异常，则采购单异常
                purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.HASERROR.getCode());
            }
            return detailEntity;
        }).collect(Collectors.toList());
        purchaseDetailService.updateBatchById(updateDetailEntities);

        // 改变采购单状态（只有所有采购项成功，采购单才成功）
        this.updateById(purchaseEntity);

        // 3、将成功采购的入库
        List<Long> itemIds = purchaseDoneVo.getItems().stream()
                .filter(itemVo -> !WareConstant.PurchaseDetailStatusEnum.HASERROR.equalsCodeTo(itemVo.getStatus()))
                .map(PurchaseDoneVo.PurchaseItemDoneVo::getItemId).collect(Collectors.toList());
        Collection<PurchaseDetailEntity> selectDetailEntities = purchaseDetailService.listByIds(itemIds);
        selectDetailEntities.forEach(entity -> wareSkuService.addStock(entity.getSkuId(), entity.getWareId(), entity.getSkuNum()));
    }

}